package com.yangming.springboot.service;


import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.yangming.springboot.dao.ModuleDao;
import com.yangming.springboot.dao.PermissionDao;
import com.yangming.springboot.dao.RoleDao;
import com.yangming.springboot.query.RoleQuery;
import com.yangming.springboot.utils.AssertUtil;
import com.yangming.springboot.vo.Permission;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.management.relation.Role;
import java.util.*;

@Service
public class RoleService {

    @Autowired
    private RoleDao roleDao;

    @Autowired
    private PermissionDao permissionDao;

    @Autowired
    private ModuleDao moduleDao;

    public List<Map<String, Object>> queryAllRole(Integer userId){
        return roleDao.queryAllRole(userId);
    }

    public Map<String, Object> queryRoleByParams(RoleQuery roleQuery){
        Map<String, Object> map = new HashMap<String, Object>();
        PageHelper.startPage(roleQuery.getPage(), roleQuery.getLimit());
        PageInfo<Role> pageInfo = new PageInfo<Role>(roleDao.selectByRoleParams(roleQuery));
        map.put("code", 0);
        map.put("msg", "");
        map.put("count", pageInfo.getTotal());
        map.put("data", pageInfo.getList());
        return map;
    }

    public void addGrant(Integer[] mids, Integer roleId){
        /*
        * 先删除原始权限记录，
        * 后批量添加新的角色权限
        * 一次操作满足新增和更新两种对权限的操作方式
        * */
        int count = permissionDao.countPermissionByRoleId(roleId);
        if (count > 0){
            permissionDao.deletePermissionByRoleId(roleId);
        }

        if (mids != null && mids.length >0){
            List<Permission> permissions = new ArrayList<Permission>();

            for (Integer mid : mids){
                Permission permission = new Permission();
                permission.setCreateDate(new Date());
                permission.setModuleId(mid);
                permission.setRoleId(roleId);
                permission.setUpdateDate(new Date());
                permission.setAclValue(moduleDao.selectByRoleId(roleId).getOptValue());
                permissions.add(permission);
            }

            AssertUtil.isTrue(permissionDao.insertBatchPermission(permissions) != permissions.size(), "add permission error");

        }
    }
}
